//
//  GKNovelTableController.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2020/9/8.
//  Copyright © 2020 wangws1990. All rights reserved.
//

import UIKit
import MBProgressHUD
import SwiftyJSON

class GKNovelTableController: BaseTableViewController {
    public weak var delegate :GKBookDelegate? = nil
    public func setBook(bookId :String,chapter :NSInteger,listChapter :[JSON]){
        self.bookId = bookId
        self.chapter = chapter
        self.listChapter = listChapter
        self.currentChapter = chapter
        if self.listChapter.count > 0 {
            self.listData.removeAll()
            self.loadData(page: 0,need: true)
        }else{
            self.endRefreshFailure()
        }
    }
    public func setChapterDatas(_ listChapter :[JSON]){
        self.listChapter = listChapter;
    }
    public func setEmpty(_ empty :Bool = true){
        if empty {
            self.listData.removeAll()
        }
        self.emptyDataImageV.isHidden = !empty
    }
    public func reloadUI(){
        self.setTheme()
        DispatchQueue.global().async {
            self.listData.forEach { content in
                content.pageContent()
            }
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
    }
    private lazy var listData : [GKContent] = {
        return []
    }()
    private lazy var listChapter : [JSON] = {
        return []
    }()
    private var bookId :String? = nil
    private var chapter:Int = 0
    private var currentChapter :Int = 0
    private lazy var mainView: UIImageView = {
        let mainView : UIImageView = UIImageView()
        mainView.isUserInteractionEnabled = false
        return mainView;
    }()
    private lazy var emptyDataImageV: UIImageView = {
        let mainView : UIImageView = UIImageView()
        mainView.isUserInteractionEnabled = false
        mainView.image = UIImage(named: "ic_search_data_empty")
        mainView.isHidden = true
        return mainView
    }()
    private lazy var titleLab: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14)
        label.textAlignment = .left
        return label
    }()
    private lazy var batteryView: GKBookBatteryView = {
        var readView = GKBookBatteryView()
        readView.backgroundColor = UIColor.clear;
        readView.isHidden = true
        return readView
    }()
    deinit {
        self.removeNotification()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.scrollsToTop = false
        if #available(iOS 11.0, *) {
            self.tableView.contentInsetAdjustmentBehavior = .never
        } else {

        }
        self.tableView.backgroundColor = UIColor.clear
        self.tableView.estimatedRowHeight = 0
        self.tableView.showsVerticalScrollIndicator = false
        self.tableView.decelerationRate = .fast
        self.view.addSubview(self.mainView)
        self.view.sendSubviewToBack(self.mainView)
        self.mainView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        self.view.addSubview(self.titleLab)
        self.view.addSubview(self.batteryView)
        self.view.addSubview(self.emptyDataImageV)
        self.emptyDataImageV.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        self.view.backgroundColor = UIColor.clear
        self.view.frame.size.width > self.view.frame.size.height ? self.landscape() : self.portrait()
        self.addNotification()
        self.setTheme()
    }
    func addNotification(){
        NotificationCenter.default.addObserver(forName: UIDevice.batteryLevelDidChangeNotification, object: nil, queue: OperationQueue.main) { [weak self] nation in
            debugPrint(nation)
            self?.batteryView.reloadThemeUI()
        }
       
    }
    func removeNotification(){
        NotificationCenter.default.removeObserver(self, name: UIDevice.batteryLevelDidChangeNotification, object: nil)
    }
    //MARK:1下拉 2、上拉 0、第一次
    override func refreshData(page: Int) {
        loadData(page: page)
    }
    func loadData(page :Int,need :Bool = false){
        let currentSize = self.tableView.contentSize;
        guard let bookId = self.bookId else { return }
        if self.listChapter.count == 0 {
            return
        }
        if(page == 1){
            if self.chapter != self.currentChapter{
                self.chapter = self.currentChapter
            }
            self.chapter = self.chapter == 0 ? 0 : self.chapter - 1
        }else if(page > 1){
            if self.chapter != self.currentChapter{
                self.chapter = self.currentChapter
            }
            self.chapter = self.listChapter.count > self.chapter + 1 ? self.chapter + 1 : self.chapter
        }
        if self.listChapter.count > self.chapter{
            let json = self.listChapter[self.chapter]
            guard let chap = GKChapter.deserialize(from: json.rawString()) else { return }
            let haveData = self.listData.contains { content in
                return content.chapterId == chap.chapterId
            }
            if haveData {
               // self.tableView.reloadData()
                self.endRefreshFailure()
                return
            }
            if  self.isrefreshing {
                return
            }
            self.isrefreshing = true
            if let content = chap.content,content.content.count > 0 {
                if(page == 1){
                    self.insertData(content: content,size: currentSize)
                }else{
                    self.appendData(content: content)
                }
                self.endRefresh(more:(self.listChapter.count) > self.chapter)
            }else{
                if need{
                    MBProgressHUD.showHUD(self.view, canTap: true, animated: true)
                }
                GKCacheData.getCache(bookId: bookId, json: json) { content in
                    MBProgressHUD.hideHUD(self.view, animated: true)
                    if(page == 1){
                        self.insertData(content: content,size: currentSize)
                    }else{
                        self.appendData(content: content)
                    }
                    self.endRefresh(more:(self.listChapter.count) > self.chapter)
                } failure: { error in
                    MBProgressHUD.hideHUD(self.view, animated: true)
                    self.endRefresh(more:(self.listChapter.count) > self.chapter)
                }

            }
        }else{
            self.endRefreshFailure()
        }
        self.getBeforeData()
        self.getAfterdata()
    }
    private var isrefreshing :Bool = false
    func insertData(content :GKContent,size :CGSize){
        DispatchQueue.global().async {
            content.pageContent()
            //定位
            let height = CGFloat(content.pageArray.count) * (content.size.height)
            let haveData = self.listData.contains { info in
                return content.chapterId == info.chapterId
            }
            DispatchQueue.main.async {
                if !haveData {
                    self.listData.insert(content, at: 0)
                    self.tableView.reloadData()
                    self.tableView.setContentOffset(CGPoint.init(x: 0, y: height), animated: false)
                }
                self.isrefreshing = false
            }
        }
    }
    func appendData(content :GKContent){
        DispatchQueue.global().async {
            content.pageContent()
            let haveData = self.listData.contains { info in
                return content.chapterId == info.chapterId
            }
            DispatchQueue.main.async {
                if !haveData {
                    self.listData.append(content)
                    self.tableView.reloadData()
                }
                self.isrefreshing = false
            }
        }
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        return self.listData.count
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let content = self.listData[section]
        return content.pageArray.count
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let content = self.listData[indexPath.section]
        return content.size.height
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if self.listData.count == section + 1 && self.listChapter.count > self.listData.count{
            return 25
        }
        return 0.01
    }
    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 25))
        button.tag = section
        //button.addTarget(self, action: #selector(loadMoreData(button:)), for: .touchUpInside)
        button.backgroundColor = UIColor.clear
        button.setTitleColor(UIColor.appx666666(), for: .normal)
        button.setTitle("正在加载下一话...", for: .normal)
        button.isHidden = true;
        
        if self.listData.count == section + 1{
            button.isHidden = false
            if let last = self.listData.last{
                if let chap = self.listChapter.last{
                    button.isHidden = last.chapterId == chap["id"].rawString()
                }
            }
        }
        return button
    }
    @objc func loadMoreData(button :UIButton){
        self.loadFootData(button.tag)
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = self.listData[indexPath.section]
        let cell = BBookScrollTableCell.cellForTableView(tableView: tableView, indexPath: indexPath)
        cell.setModel(model: model, indexPath: indexPath)
        self.setVisibleModel()
        return cell
    }
    
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        debugPrint("willDisplayHeaderView \(section)")
        if section == 0 && self.listData.count > section{
            let content = self.listData[section]
            self.setModel(model: content, pageIndex: 0)
        }
        if self.chapter == 0 && section <= 1{
            return
        }
        self.refreshData(page: 1)
    }
    func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
        debugPrint("willDisplayFooterView \(section)")
        self.loadFootData(section)
    }
    func loadFootData(_ section :Int){
        if self.chapter + 1 >= self.listChapter.count && section >= 1 {
            return
        }
        self.refreshData(page: 2)
    }
    func setVisibleModel(){
        if let dataCells = self.tableView.indexPathsForVisibleRows{
            if let indexPath = dataCells.last{
                if self.listData.count > indexPath.section{
                    let model = self.listData[indexPath.section]
                    self.setModel(model: model, pageIndex: indexPath.row)
                    self.setCurrentPageIndex(model: model, pageIndex: indexPath.row)
                }
            }
        }
    }
    func setModel(model :GKContent, pageIndex :Int){
        self.titleLab.text = model.title
        self.batteryView.loadData(pageIndex: pageIndex + 1, total: model.pageArray.count)
        self.batteryView.isHidden = false
    }
    func setCurrentPageIndex(model :GKContent,pageIndex :Int){
        let chapter = self.listChapter.firstIndex { chap in
            return chap["id"].rawString() == model.chapterId
        }
        if let chapterIndex = chapter {
            self.currentChapter = chapterIndex
            guard let delegate = self.delegate else { return }
            delegate.viewDidAppear(chapter: chapterIndex, pageIndex: pageIndex,content: model)
        }
    }
    func getBeforeData(){
        let chapter = self.chapter - 1
        if chapter >= 0 && self.listChapter.count > chapter {
            let info = self.listChapter[chapter]
            self.loadData(info)
        }
    }
    func getAfterdata(){
        let chapter = self.chapter + 1
        if chapter >= 0 && listChapter.count > chapter {
            let info = listChapter[chapter]
            self.loadData(info)
        }
    }
    func loadData(_ json :JSON){
        let chapterId = json["id"].stringValue
        guard let bookId = self.bookId else { return }
        let jsonContent = ApiCache.values(key: chapterId).json
        if jsonContent.isEmpty && jsonContent.count == 0 {
            GKCacheData.getCache(bookId: bookId, json: json) { object in
                if let js = object.toJSON(){
                    ApiCache.set(object: js, key: chapterId)
                }
            } failure: { error in
                
            }
        }
    }
    private func portrait(){
        self.titleLab.isHidden = false
        self.titleLab.snp.remakeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalToSuperview().offset(STATUS_BAR_HIGHT - 10)
        }
        self.batteryView.snp.remakeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(20 + TAB_BAR_ADDING)
        }
        self.tableView.snp.remakeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalToSuperview().offset(STATUS_BAR_HIGHT + 10)
            make.bottom.equalToSuperview().offset( -20 - TAB_BAR_ADDING)
        }
    }
    private func landscape(){
        self.titleLab.isHidden = true
        self.batteryView.snp.remakeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(0)
            make.height.equalTo(20)
        }
        self.tableView.snp.remakeConstraints { make in
            make.left.equalTo(self.view.safeAreaLayoutGuide)
            make.right.equalTo(self.view.safeAreaLayoutGuide)
            make.top.equalTo(self.view.safeAreaLayoutGuide)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide)
        }
    }
    private func setTheme(){
        let hex = moya.bookSet.theme.themeColor
        self.mainView.image = UIImage.imageWithColor(color: UIColor(hex: hex))
        self.titleLab.textColor = UIColor(hex: moya.bookSet.theme.fontColor)
        self.batteryView.reloadThemeUI()
    }
    override var shouldAutorotate: Bool{
        return true
    }
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return [.portrait,.landscapeRight]
    }
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
        return .portrait
    }
    override var refreshColor: UIColor{
        return UIColor.clear
    }
}
